<template>
  <canvas
    canvas-id="myCanvas"
    class="canvas"
    :style="{
      width: `${canvas.width}px`,
      height: `${canvas.height}px`,
      position: 'fixed',
      bottom: '-1000px',
    }"
  ></canvas>
</template>
<script>
import { drawSquarePic, drawTextReturnH } from "@/wxutil/canvas";
export default {
  props: {
    //画布大小
    canvas: {
      type: Object,
      default: {
        width: 0,
        height: 0,
      },
    },
    //画布内容
    canvasList: {
      type: Array,
      default: [],
    },
    //画布背景颜色
    backgroundColor: {
      type: String,
      default: "rgba(0,0,0,0)",
    },
    show: { type: Boolean, default: false },
  },
  watch: {
    show: {
      handler(newVal) {
        newVal && this.createPoster();
      },
    },
  },
  data() {
    return {
      ctxRes: null,
    };
  },

  methods: {
    async createPoster() {
      uni.showLoading({
        title: "模板生成中···",
        mask: true,
      });
      const ctx = this.ctxRes;
      ctx.draw(); //清空之前的海报
      // 绘制背景
      ctx.setFillStyle(this.backgroundColor);
      ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
      for (let i = 0; i < this.canvasList.length; i++) {
        const element = this.canvasList[i];
        if (element.type === "text") {
          console.log("绘制文本：", element.text);
          await drawTextReturnH(ctx, element);
        } else if (element.type.includes("image")) {
          console.log("绘制图片：", element.path);
          await drawSquarePic(ctx, element);
        }
      }
      setTimeout(() => {
        this.$emit("finish");
        this.handleSaveCanvasImage();
      }, 500);

      uni.hideLoading();
    },
    /**
     * @description: 保存到系统相册
     * @param {type}
     * @return {type}
     * @author: hch
     */
    handleSaveCanvasImage() {
      uni.showLoading({
        title: "保存中...",
      });
      let _this = this;
      // 把画布转化成临时文件
      // #ifndef MP-ALIPAY
      // 支付宝小程序外，其他都是用这个方法 canvasToTempFilePath
      uni.canvasToTempFilePath(
        {
          canvasId: "myCanvas",
          success: async function (res) {
            //保存图片至相册
            // #ifndef H5
            // 除了h5以外的其他端
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.hideLoading();
                uni.showToast({
                  title: "图片保存成功，可以去分享啦~",
                  duration: 2000,
                  icon: "none",
                });
                // _this.handleCanvasCancel();
              },
              fail: () => {
                uni.showToast({
                  title: "保存失败，稍后再试",
                  duration: 2000,
                  icon: "none",
                });
                uni.hideLoading();
              },
              complete: () => {
                // _this.$emit("finish");
              },
            });
            // #endif

            // #ifdef H5
            // h5的时候
            uni.showToast({
              title: "请长按保存",
              duration: 3000,
              icon: "none",
            });
            // _this.handleCanvasCancel();
            // 预览图片
            uni.previewImage({
              urls: [res.tempFilePath],
            });
            // #endif
          },
          fail(res) {
            console.log("fail -> res", res);
            uni.showToast({
              title: "保存失败，稍后再试",
              duration: 2000,
              icon: "none",
            });
            uni.hideLoading();
          },
        },
        this
      );
      // #endif
    },
  },
  created() {
    this.ctxRes = uni.createCanvasContext("myCanvas", this);
  },
};
</script>


<style scoped  lang='scss'>
</style>